import { useLocation } from 'react-router-dom';

export function openWindowFeature(
	url: string,
	search?: Record<PropertyKey, any>,
	options: {
		fullScreen?: boolean;
		width?: number;
		height?: number;
		top?: number;
		left?: number;
	} = {}
) {
	try {
		// 获取url地址/域名
		const hasForwardSlash = /^\/.*$/.test(url);
		const origin = window.location.origin + (hasForwardSlash ? '' : '/');
		// 生成url参数
		const urlSearch = search ? '?' + new URLSearchParams(search).toString() : '';

		let size = '';
		if (options?.fullScreen) {
			const width = document.documentElement.clientWidth;
			const height = document.documentElement.clientHeight;

			size = `width=${width},height=${height},top=500`;
		} else {
			const { width = 800, height = 500, top = 500, left = 300 } = options;

			size = `width=${width},height=${height},top=${top},left=${left}`;
		}

		window.open(
			`${origin + url}${urlSearch}`,
			'_blank',
			`${size},toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no,alwaysRaised=yes,depended=yes,titlebar=no`
		);
	} catch (err: any) {
		console.error(err.message);
	}
}

/** 获取url上的参数，以对象形式返回 */
export function useUrlParams<T = { [key: string]: string }>(): T {
	const paramsStr = useLocation().search;
	const params = new URLSearchParams(paramsStr);
	return Object.fromEntries(params) as T;
}
